package com.framework.common.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class ClassTypeHelper {

    public static <T> T newInstnace(Class<T> clazz) throws ReflectiveOperationException {
        Constructor<T> constructor = clazz.getConstructor();
        return constructor.newInstance();
    }

    public static <T> T newInstnace2(Object o) {
        try {
            Type type = o.getClass().getGenericSuperclass();
            if (type == null) {
                return null;
            }
            ParameterizedType parameterizedType = null;
            if (type instanceof ParameterizedType) {
                parameterizedType = (ParameterizedType) type;
            }
            if (parameterizedType == null) {
                return null;
            }
            Type[] types = parameterizedType.getActualTypeArguments();
            if (types.length == 0) {
                return null;
            }
            Type realType = parameterizedType.getActualTypeArguments()[0];
            Class<T> clz = (Class<T>) realType;
            return clz.newInstance();

        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
